package com.keai.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.keai.dao.MenuDao;
import com.keai.dao.PermissionDao;
import com.keai.dao.RoleDao;
import com.keai.dao.UserDao;
import com.keai.entity.PageResult;
import com.keai.entity.QueryPageBean;
import com.keai.pojo.Menu;
import com.keai.pojo.Permission;
import com.keai.pojo.Role;
import com.keai.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
   String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Autowired
    UserDao userDao;

    @Autowired
    RoleDao roleDao;

    @Autowired
    PermissionDao permissionDao;
    @Autowired
    MenuDao menuDao;


    /**
     * 根据用户名查询用户信息（包含角色，和角色对应的权限）
     * 1. 根据用户名查询用户信息
     * 2. 根据用户id查询相应的角色对象
     * 3. 根据角色id查询相应的权限对象
     * 4. 组合
     */
    @Override
    public SysUser findByUsername(String username) {
        //1. 根据用户名查询用户信息
        SysUser sysUser = userDao.findByUsername(username);
        if(sysUser == null){
            return null;
        }
        System.out.println(sysUser.getPassword());
        //2. 根据用户id查询相应的角色对象
        Set<Role> roles = roleDao.findRoleListByUserId(sysUser.getId());
        if(roles == null || roles.size() == 0){
            return sysUser;
        }
        //3. 根据角色id查询相应的权限对象
        for (Role role : roles) {
            Set<Permission> permissions = permissionDao.findPermissionListByRoleId(role.getId());
            role.setPermissions(permissions);
        }
        //4. 组合
        sysUser.setRoles(roles);
        return sysUser;
    }

    @Override
    public List<Map<String, Object>> findMenu(String username) {

        this.username=username;
        List<Map<String,Object>>menuMapList=new ArrayList<>();
        //获取到用户
        SysUser sysUser = userDao.findByUsername(username);
        //获取到用户对应的角色集合
        Set<Role> roles = roleDao.findRoleListByUserId(sysUser.getId());
        ArrayList<Menu> parentMenus=new ArrayList<>();
        List<Menu>childMenus=new ArrayList<>();
        //遍历角色集合
        for (Role role : roles) {
            //查询角色所对应的菜单集合
            List<Menu>menuList=menuDao.findMenu(role.getId());
            for (Menu menu : menuList) {
                if (menu.getLevel()==1){
                    parentMenus.add(menu);
                    System.out.println("//"+menu);
                }else {
                    System.out.println(menu);
                    childMenus.add(menu);
                }
            }
        }

        for (Menu parentMenu : parentMenus) {
            Map<String,Object> parentMenuMap=new LinkedHashMap<>();
            List<Map<String,Object>>childList=new ArrayList<>();
            for (Menu childMenu : childMenus) {
                if (parentMenu.getId()== childMenu.getParentMenuId()){
                    Map<String,Object> childMenuMap=new LinkedHashMap<>();
                    childMenuMap.put("path",childMenu.getPath());
                    childMenuMap.put("title",childMenu.getName());
                    childMenuMap.put("linkUrl",childMenu.getLinkUrl());
                    childMenuMap.put("children",childMenu.getChildren());
                    childList.add(childMenuMap);
                    parentMenu.setChildren(childList);
                }
            }
            parentMenuMap.put("path",parentMenu.getPath());
            parentMenuMap.put("title",parentMenu.getName());
            parentMenuMap.put("icon",parentMenu.getIcon());
            parentMenuMap.put("children",parentMenu.getChildren());
            menuMapList.add(parentMenuMap);
        }
        return menuMapList;

    }
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //开启分页。
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //开始条件查询
        Page<SysUser> page=userDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page);
    }

    @Override
    @Transactional
    public void add(Integer[] roleIds, SysUser user) {
        //需要回显主键
        userDao.add(user);
        //根据角色的回显主键和permissionIds数组对中间表进行维护
        if (user.getId()!=null &&roleIds!=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                userDao.set(user.getId(),roleId);
            }
        }else{
            throw new RuntimeException("权限和角色中间表维护失败");
        }

    }

    @Override
    public SysUser findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public Integer[] findUserIdsByUserId(Integer id) {
        return userDao.findUserIdsByUserId(id);
    }



    @Override
    @Transactional
    public void edit(Integer[] roleIds, SysUser user) {
        //1.修改用户
        userDao.update(user);
        //2.1 先删除该用户原来的关系角色
        userDao.deleteAssociation(user.getId());

        //2.2添加新的关系
        if (user.getId() != null && roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                userDao.set(user.getId(),roleId);
            }
        }

    }

    @Override
    @Transactional
    public void delById(Integer id) {
//           1.   先删除用户与角色的关系
        userDao.deleteAssociation(id);
//               再删除角色
        userDao.delById(id);

    }


}
